//
//  RootViewController.m
//  iCarStyle
//
//  Created by liu nian on 13-9-9.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "RootViewController.h"
#import "NewsViewController.h"
#import "InsuranceController.h"
#import "MainViewController.h"
#import "RescueController.h"
#import "FavViewController.h"
#import "AboutController.h"
#import "RNFrostedSidebar.h"
#import "WeatherView.h"
#import "MKNavigationController.h"
#import "DataEnvironment.h"
#import "RKTabView.h"

#define kDefaultAnimationIntervalSlow     1.0f
#define kDefaultAnimationIntervalMedium   0.5f
#define kDefaultAnimationIntervalFast     0.3f
#define kDefaultAnimationIntervalFaster   0.2f

@interface RootViewController ()<RNFrostedSidebarDelegate,UIGestureRecognizerDelegate,RKTabViewDelegate>{
    CGRect          _orignFrame;
    CGFloat     _kSpaceHeight ;
}
@property (nonatomic, retain) NewsViewController *newsController;
@property (nonatomic, retain) InsuranceController *insuranceController;
@property (nonatomic, retain) MainViewController *mainController;
@property (nonatomic, retain) RescueController *rescueController;
@property (nonatomic, retain) FavViewController *favController;
@property (nonatomic, retain) AboutController *aboutController;
@property (nonatomic, retain) UIView    *containerView;
@property (nonatomic, strong) WeatherView *weatherView;
@property (nonatomic, retain) UIPanGestureRecognizer *panGesture;

@property (nonatomic, retain) RKTabView *tabView;
@end

@implementation RootViewController

- (id)init
{
    self = [super init];
    if (self) {
        // Custom initialization
        [DataEnvironment sharedDataEnvironment].rootViewController = self;
        self.panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
        [self.panGesture setMaximumNumberOfTouches:2];
        self.panGesture.delegate = self;
        [self.view addGestureRecognizer:self.panGesture];
        self.slideEnabled = YES;
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleAppDidEnterBackground:)
                                                     name:UIApplicationDidEnterBackgroundNotification
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleAppWillEnterForeground:)
                                                     name:UIApplicationWillEnterForegroundNotification
                                                   object:nil];
        

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _kSpaceHeight = 0;
//#if __IPHONE_OS_VERSION_MAX_ALLOWED < 70000
//    
//#else
//    float systemName = [[[UIDevice currentDevice] systemVersion] floatValue];
//    if(systemName >= 7.0)
//    {
//        self.edgesForExtendedLayout = UIRectEdgeTop;
//        self.extendedLayoutIncludesOpaqueBars = NO;
//        [self.navigationController.navigationBar setBarTintColor:[UIColor flatGrayColor]];
//        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
////        self.view.bounds = CGRectMake(0, -20, self.view.frame.size.width, self.view.frame.size.height);
//        _kSpaceHeight = 20;
//    }
//#endif
    [self.tabBar removeFromSuperview];
    
    [self.view addSubview:self.tabView];
    [self initViews];
    [self.view addSubview:self.weatherView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED < 70000

#else
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}
#endif
- (void)initViews{
    
    NSMutableArray *controllers = [[NSMutableArray alloc] initWithCapacity:5];
    
    MKNavigationController *newsNav = [[MKNavigationController alloc] initWithRootViewController:self.newsController];
//    [newsNav.navigationBar setBackgroundImage:IMGNAMED(@"bg_top.png") forBarMetrics:UIBarMetricsDefault];
    
    MKNavigationController *insuranceNav = [[MKNavigationController alloc] initWithRootViewController:self.insuranceController];
//    [insuranceNav.navigationBar setBackgroundImage:IMGNAMED(@"bg_top.png") forBarMetrics:UIBarMetricsDefault];
    
    MKNavigationController *storeNav = [[MKNavigationController alloc] initWithRootViewController:self.mainController];
    
//    [storeNav.navigationBar setBackgroundImage:IMGNAMED(@"bg_top.png") forBarMetrics:UIBarMetricsDefault];
    
    MKNavigationController *rescueNav = [[MKNavigationController alloc] initWithRootViewController:self.rescueController];
    
//    [rescueNav.navigationBar setBackgroundImage:IMGNAMED(@"bg_top.png") forBarMetrics:UIBarMetricsDefault];
    
    MKNavigationController *favNav = [[MKNavigationController alloc] initWithRootViewController:self.favController];
    
//    [favNav.navigationBar setBackgroundImage:IMGNAMED(@"bg_top.png") forBarMetrics:UIBarMetricsDefault];
    
    MKNavigationController *aboutNav = [[MKNavigationController alloc] initWithRootViewController:self.aboutController];
    
//    [aboutNav.navigationBar setBackgroundImage:IMGNAMED(@"bg_top.png") forBarMetrics:UIBarMetricsDefault];
    
    [controllers addObject:newsNav];
    [controllers addObject:insuranceNav];
    [controllers addObject:storeNav];
    [controllers addObject:favNav];
    [controllers addObject:aboutNav];

    self.viewControllers = controllers;
    
//    [self.tabBarController setViewControllers:controllers];
//    [self.containerView addSubview:self.tabBarController.view];
//    for (UIView *view in self.containerView.subviews) {
////        [view setFrame:self.view.bounds];
//        [view setFrame:CGRectOffset(view.frame, 0, CGRectGetMaxY(view.frame)> 0 ? -20 : 0)];
//    }
}
- (void)hideTabbar:(BOOL)isHidde{
    if (isHidde) {
        CGRect frame = self.tabView.frame;
        self.tabView.frame = CGRectMake(0,
                                        CGRectGetHeight(self.view.bounds),
                                        CGRectGetWidth(self.view.bounds),
                                        49);
    }else{
        self.tabView.frame = CGRectMake(0,
                                        CGRectGetHeight(self.view.bounds) - 49 - _kSpaceHeight,
                                        CGRectGetWidth(self.view.bounds),
                                        49);
    }
}

#pragma mark - handle notifications
- (void)handleAppDidEnterBackground:(NSNotification *)notification {
    [self showCover];
    if (self.weatherView.superview) {
        [self.weatherView stopImageSwitch];
    }
    
}

- (void)handleAppWillEnterForeground:(NSNotification *)notifcation {
    self.slideEnabled = YES;
    if (self.weatherView.superview) {
        [self.weatherView startImageSwitch];
    }
}
- (void)setSlideEnabled:(BOOL)slideEnabled {
    _slideEnabled = slideEnabled;
    self.panGesture.enabled = _slideEnabled;
}
#pragma mark - RKTabViewDelegate

- (void)tabView:(RKTabView *)tabView tabBecameEnabledAtIndex:(int)index tab:(RKTabItem *)tabItem {
    NSLog(@"Tab № %d became enabled on tab view", index);
    self.selectedIndex = index;
}

- (void)tabView:(RKTabView *)tabView tabBecameDisabledAtIndex:(int)index tab:(RKTabItem *)tabItem {
    NSLog(@"Tab № %d became disabled on tab view", index);
}

#pragma mark - Utility
static inline UIViewAnimationOptions animationOptionsWithCurve(UIViewAnimationCurve curve)
{
    switch (curve) {
        case UIViewAnimationCurveEaseInOut:
            return UIViewAnimationOptionCurveEaseInOut;
        case UIViewAnimationCurveEaseIn:
            return UIViewAnimationOptionCurveEaseIn;
        case UIViewAnimationCurveEaseOut:
            return UIViewAnimationOptionCurveEaseOut;
        case UIViewAnimationCurveLinear:
            return UIViewAnimationOptionCurveLinear;
    }
}

- (void)hideCover {
    if (_weatherView && _weatherView.superview) {
        [self.weatherView stopImageSwitch];
        
        CGRect frame = _weatherView.frame;
        frame.origin.x = -frame.size.width;
        
        [UIView animateWithDuration:kDefaultAnimationIntervalFast
                              delay:0.5
                            options:animationOptionsWithCurve(UIViewAnimationCurveEaseInOut)
                         animations:^{
                             _weatherView.frame = frame;
                         }
                         completion:^(BOOL finished) {
                             [_weatherView removeFromSuperview];
                         }];
    }
}
- (void)showCover {
    if (!self.weatherView.superview) {
        [self.view addSubview:self.weatherView];
        
    }
    [self.weatherView setFrame:self.view.bounds];
}

#pragma mark - UIGestureRecognizer handler method
- (void)pan:(UIPanGestureRecognizer *)gestureRecognizer {
    
    if (!self.slideEnabled) {
        return;
    }
    
    static BOOL initialized = NO;
    UIView *view = self.weatherView;
    
    CGPoint translation = [gestureRecognizer translationInView:self.view];
    
    if ((view.frame.origin.x >= 0 && translation.x > 0) ||
        (view.frame.origin.x <= -self.view.bounds.size.width && translation.x < 0)) {
        if (gestureRecognizer.state != UIGestureRecognizerStateEnded &&
            gestureRecognizer.state != UIGestureRecognizerStateRecognized &&
            gestureRecognizer.state != UIGestureRecognizerStateCancelled &&
            gestureRecognizer.state != UIGestureRecognizerStateFailed)
        {
            return;
        } else {
            if (!initialized) {
                return;
            }
        }
    }
    
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        
        if (!self.weatherView.superview) {
            [self.view addSubview:self.weatherView];
        }
        if (view.frame.origin.x <= 0) {
            [self.weatherView stopImageSwitch];
        }
        
        initialized = YES;
        
        _orignFrame = view.frame;
        view.layer.shadowColor=[UIColor blackColor].CGColor;
        view.layer.shadowOffset = CGSizeMake(4, 0);
        view.layer.shadowOpacity = 0.8;
        view.layer.shadowRadius = 3.0;
        CGPathRef path = [UIBezierPath bezierPathWithRect:CGRectMake(view.bounds.size.width-2,
                                                                     0,
                                                                     2,
                                                                     view.bounds.size.height)].CGPath;
        [view.layer setShadowPath:path];
        
    } else if ([gestureRecognizer state] == UIGestureRecognizerStateBegan ||
               [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        
        CGRect frame = view.frame;
        frame.origin.x += translation.x;
        if (frame.origin.x > 0) {
            frame.origin.x = 0;
        } else if (frame.origin.x < -self.view.bounds.size.width) {
            frame.origin.x = -self.view.bounds.size.width;
        }
        view.frame = frame;
        
        [gestureRecognizer setTranslation:CGPointZero inView:self.view];
        
    } else if (gestureRecognizer.state == UIGestureRecognizerStateEnded ||
               gestureRecognizer.state == UIGestureRecognizerStateRecognized ||
               gestureRecognizer.state == UIGestureRecognizerStateCancelled ||
               gestureRecognizer.state == UIGestureRecognizerStateFailed) {
        
        CGRect frame = view.frame;
        CGFloat deltaX = frame.origin.x - _orignFrame.origin.x;
        if (deltaX != 0) {
            if (fabs(deltaX)/self.view.bounds.size.width > (deltaX>0?0.3:0.1)) {
                frame.origin.x = deltaX>0?0:-self.view.bounds.size.width;
            } else {
                frame.origin.x = deltaX>0?-self.view.bounds.size.width:0;
            }
        }
        
        [UIView animateWithDuration:0.2f delay:0.0f options:animationOptionsWithCurve(UIViewAnimationCurveEaseIn)
                         animations:^{
                             view.frame = frame;
                         }
                         completion:^(BOOL finished) {
                             view.layer.shadowOffset = CGSizeMake(0, 0);
                             view.layer.shadowOpacity = 0;
                             if (view.frame.origin.x <0) {
                                 [self.weatherView removeFromSuperview];
                                 self.slideEnabled = NO;
                             } else {
                                 [self.weatherView startImageSwitch];
                             }
                         }];
        initialized = NO;
    }
}

#pragma mark - UIGestureRecognizer Delegate method
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    
    if ([otherGestureRecognizer.view isKindOfClass:[UIScrollView class]]) {
        UIScrollView *scrollView = (UIScrollView *)otherGestureRecognizer.view;
        if (scrollView.contentOffset.x <= 0) {
            return YES;
        }
    }
    
    return NO;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    
    //    if (self.sourceView.fingerAdView &&
    //        [touch.view isDescendantOfView:self.sourceView.fingerAdView]) {
    //        return NO;
    //    }
    return YES;
}

#pragma mark

- (WeatherView *)weatherView{
    if (!_weatherView) {
        _weatherView = [[WeatherView alloc] initWithFrame:self.view.bounds];
        _weatherView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    }
    return _weatherView;
}
#pragma mark getter
- (UIView *)containerView{
    if (!_containerView) {
        _containerView = [[UIView alloc] initWithFrame:self.view.bounds];
//        [_containerView setBackgroundColor:[UIColor whiteColor]];
        [self.view addSubview:_containerView];
    }
    return _containerView;
}
- (RKTabView *)tabView{
    if (!_tabView) {
        
        RKTabItem *filtersTabItem = [RKTabItem createUsualItemWithImageEnabled:[UIImage imageNamed:@"image-5"]
                                                                 imageDisabled:[UIImage imageNamed:@"image-5"]];
        filtersTabItem.titleString = @"知识";
        filtersTabItem.tabState = TabStateEnabled;
        filtersTabItem.titleFontColor = [UIColor darkGrayColor];
        filtersTabItem.titleFontColor = [UIColor darkGrayColor];
        
        RKTabItem *frameTabItem = [RKTabItem createUsualItemWithImageEnabled:[UIImage imageNamed:@"image-6"]
                                                               imageDisabled:[UIImage imageNamed:@"image-6"]];
        frameTabItem.titleString = @"车险";
        frameTabItem.titleFontColor = [UIColor darkGrayColor];
        RKTabItem *rotateTabItem = [RKTabItem createUsualItemWithImageEnabled:[UIImage imageNamed:@"image-9"]
                                                                imageDisabled:[UIImage imageNamed:@"image-9"]];
        rotateTabItem.titleString = @"图文";
        rotateTabItem.titleFontColor = [UIColor darkGrayColor];
        RKTabItem *contrastTabItem = [RKTabItem createUsualItemWithImageEnabled:[UIImage imageNamed:@"image-7"]
                                                                  imageDisabled:[UIImage imageNamed:@"image-7"]];
        contrastTabItem.titleString = @"收藏";
        contrastTabItem.titleFontColor = [UIColor darkGrayColor];
        RKTabItem *brightnessTabItem = [RKTabItem createUsualItemWithImageEnabled:[UIImage imageNamed:@"image-8"]
                                                                    imageDisabled:[UIImage imageNamed:@"image-8"]];
        brightnessTabItem.titleString = @"关于";
        brightnessTabItem.titleFontColor = [UIColor darkGrayColor];
        
        _tabView = [[RKTabView alloc] initWithFrame:CGRectMake(0,
                                                               CGRectGetHeight(self.view.bounds) - 49 - _kSpaceHeight,
                                                               CGRectGetWidth(self.view.bounds),
                                                               49)
                                        andTabItems:[NSArray arrayWithObjects:filtersTabItem,frameTabItem,rotateTabItem,contrastTabItem,brightnessTabItem, nil]];
        _tabView.horizontalInsets = HorizontalEdgeInsetsMake(25, 25);
        _tabView.darkensBackgroundForEnabledTabs = YES;
        _tabView.enabledTabBackgrondColor = [UIColor flatGrayColor];
        _tabView.backgroundColor = [UIColor flatWhiteColor];
        _tabView.drawSeparators = YES;
        _tabView.delegate = self;
    }
    return _tabView;
}

- (NewsViewController *)newsController{
    if (!_newsController) {
        _newsController = [[NewsViewController alloc] init];
    }
    return _newsController;
}
- (InsuranceController *)insuranceController{
    if (!_insuranceController) {
        _insuranceController = [[InsuranceController alloc] init];
    }
    return _insuranceController;
}
- (MainViewController *)mainController{
    if (!_mainController) {
        _mainController = [[MainViewController alloc] init];
    }
    return _mainController;
}
- (RescueController *)rescueController{
    if (!_rescueController) {
        _rescueController = [[RescueController alloc] init];
    }
    return _rescueController;
}

- (FavViewController *)favController{
    if (!_favController) {
        _favController = [[FavViewController alloc] init];
    }
    return _favController;
}

- (AboutController *)aboutController{
    if (!_aboutController) {
        _aboutController = [[AboutController alloc] init];
    }
    return _aboutController;
}
@end
